package cn.fscode.code.generator.controller.system;

import cn.fscode.commons.core.response.Resp;
import cn.fscode.code.generator.model.po.SysDictItemPO;
import cn.fscode.code.generator.model.po.SysDictPO;
import cn.fscode.code.generator.model.req.SysDictQueryReq;
import cn.fscode.code.generator.service.ISysDictService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.Map;

/**
 * 数据字典信息
 * 
 * @author shenguangyang
 */
@Api(tags = "字典管理")
@Validated
@RestController
@RequestMapping("/api/sys/dict")
public class SysDictController {
    @Resource
    private ISysDictService dictService;

    @ApiOperation("获取字典列表")
    @GetMapping("/pageDict")
    public Resp<IPage<SysDictPO>> pageDict(@Validated SysDictQueryReq req) {
        IPage<SysDictPO> page = dictService.pageDict(req);
        return Resp.ok(page);
    }

    @ApiOperation("查询全部字典条目")
    @GetMapping("/listAllDictItem")
    public Resp<Map<String, List<SysDictItemPO>>> listAllDictItem() {
        Map<String, List<SysDictItemPO>> result = dictService.listAllDictItem();
        return Resp.ok(result);
    }

    /**
     * 查询字典类型详细
     */
    @ApiOperation("查询字典")
    @GetMapping(value = "/get")
    public Resp<SysDictPO> get(@RequestParam(value = "id") Long dictId) {
        return Resp.ok(dictService.getById(dictId));
    }

    /**
     * 新增字典类型
     */
    @ApiOperation("新增字典")
    @PostMapping("/save")
    public Resp<?> save(@Validated @RequestBody SysDictPO dict) {
        return dictService.saveDict(dict) > 0 ? Resp.ok() : Resp.fail("保存失败");
    }

    /**
     * 修改字典类型
     */
    @ApiOperation("修改字典类型")
    @PostMapping("/update")
    public Resp<?> update(@Validated @RequestBody SysDictPO dict) {
        return dictService.updateDict(dict) > 0 ? Resp.ok() : Resp.fail("更新失败");
    }

    /**
     * 删除字典类型
     */
    @ApiOperation("批量删除字典类型")
    @DeleteMapping("/deleteBatch")
    public Resp<?> deleteBatch(@RequestParam(value = "ids") Long[] dictIds) {
        dictService.deleteBatchByIds(dictIds);
        return Resp.ok();
    }

    /**
     * 删除字典类型
     */
    @ApiOperation("删除字典类型")
    @DeleteMapping("/delete")
    public Resp<?> delete(@RequestParam(value = "id") @NotNull(message = "字典id是必填项") Long dictId) {
        dictService.deleteById(dictId);
        return Resp.ok();
    }

    /**
     * 刷新字典缓存
     */
    @ApiOperation("刷新字典缓存")
    @GetMapping("/refleshCache")
    public Resp<?> refreshCache() {
        dictService.resetDictCache();
        return Resp.ok();
    }
}